package com.example.glidedemo.presenter;


import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;


import com.example.glidedemo.common.WeakRrfHandler;
import com.example.glidedemo.contract.MovieContract;
import com.example.glidedemo.entity.MovieEntity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MoviePresenter implements MovieContract.IMoviePresenter {
    public static final int HTTP_SUCCESS = 0;
    public static final int HTTP_SUCCESS2 = 10;
    public static final int HTTP_FAIL = 1;
    private MovieContract.IMovieView mMovieView;

    public MoviePresenter(MovieContract.IMovieView view) {
        mMovieView = view;
    }

    @Override
    public void getData() {
        MovieService service = GlobalRetrofitClient.getInstance().create(MovieService.class);
        service.getMovie().enqueue(new Callback<MovieEntity>() {
            @Override
            public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
                Message message = Message.obtain();
                message.obj = response.body();
                message.what = HTTP_SUCCESS;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<MovieEntity> call, Throwable t) {

            }
        });
    }

    WeakRrfHandler<MoviePresenter> mHandler =
            new WeakRrfHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message msg) {
                    int result = msg.what;
                    switch (result) {
                        case HTTP_SUCCESS:
                            MovieEntity movie = (MovieEntity) msg.obj;
                            if (mMovieView != null) {
                                mMovieView.showData(movie);
                            }
                            break;
                        case HTTP_FAIL:
                            break;
                    }
                    return false;
                }
            });
}